package cn.mapway.ib.module;

import cn.mapway.ib.share.model.common.ApiResult;
import cn.mapway.ib.share.model.dir.DirFile;
import io.swagger.annotations.Api;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Files;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.GET;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Api("dir")
@At("/dir")
@IocBean(create = "init", depose = "depose")
public class DirModule {
    @Inject
    protected PropertiesProxy conf;

    @At
    @GET
    @Ok("json")
    public ApiResult<List<DirFile>> list(@Param("dir") String dir) {

        return extractDir(dir);
    }

    @At
    @GET
    @Ok("json")
    public ApiResult<List<DirFile>> files(@Param("dir") String dir) {
        return extractFile(dir);
    }

    private ApiResult<List<DirFile>> extractFile(String dir) {
        String path = "/";
        if (!Strings.isBlank(dir)) {
            path = dir;
        }
        File file = new File(path);
        if (file.isFile()) {
            return ApiResult.fail("访问的是一个文件");
        }
        List<DirFile> data = new ArrayList<>();
        File[] files = Files.files(file, null);
        if (files != null) {
            for (File f : files) {
                DirFile dirFile = new DirFile();
                dirFile.setLocation(f.getAbsolutePath());
                dirFile.setSize(f.length());
                dirFile.setLastModifyTime(f.lastModified());
                dirFile.setDirectory(f.isDirectory());
                data.add(dirFile);
            }
        }
        return ApiResult.ok(data);
    }

    private ApiResult<List<DirFile>> extractDir(String dir) {
        String path = "/";
        if (!Strings.isBlank(dir)) {
            path = dir;
        }
        File file = new File(path);
        if (file.isFile()) {
            return ApiResult.fail("访问的是一个文件");
        }
        List<DirFile> data = new ArrayList<>();
        File[] dirs = Files.dirs(file);
        if (dirs != null) {
            for (File f : dirs) {
                DirFile dirFile = new DirFile();
                dirFile.setLocation(f.getAbsolutePath());
                dirFile.setSize(f.length());
                dirFile.setLastModifyTime(f.lastModified());
                dirFile.setDirectory(f.isDirectory());
                data.add(dirFile);
            }
        }
        return ApiResult.ok(data);
    }

    public void init() {

    }

    public void depose() {

    }
}
